package bimvu.yolaguidebook;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class SiteRowAdapter extends BaseAdapter {

    private static LayoutInflater inflater = null;
    private List<Site> sites;
    private Context context;

    public SiteRowAdapter(Context context, List<Site> sites) {
        this.context = context;
        this.sites = sites;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return sites.size();
    }

    @Override
    public Object getItem(int i) {
        return sites.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rowView = view;
        if (rowView == null) {
            rowView = inflater.inflate(R.layout.site_row, null);
        }

        Site site = sites.get(i);

        Resources res = context.getResources();
        int thumbId = res.getIdentifier(site.thumbKey, "drawable", context.getPackageName());

        ImageView thumbView = (ImageView) rowView.findViewById(R.id.siteThumb);
        thumbView.setImageResource(thumbId);

        TextView titleText = (TextView) rowView.findViewById(R.id.siteTitle);
        titleText.setText(site.title);

        TextView addressText = (TextView) rowView.findViewById(R.id.siteAddress);
        if (!site.address.isEmpty()) {
            addressText.setText(site.address);
        } else {
            addressText.setVisibility(View.GONE);
        }

        if (site.distance != null) {
            TextView distanceText = (TextView) rowView.findViewById(R.id.distance);
            int distanceInMeters = Math.round(site.distance);
            int kilometers = distanceInMeters / 1000;
            int meters = distanceInMeters % 1000;
            String distanceString = (kilometers > 0) ? kilometers + " км " : "";
            distanceString += (meters > 0) ? meters + " м" : "";
            distanceText.setText(distanceString);
        }

        return rowView;
    }
}
